package com.rpctest.myrpc.server;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;//?
import org.springframework.context.event.ContextRefreshedEvent;//?
import org.springframework.stereotype.Component;

import javax.swing.table.TableRowSorter;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @ClassName BioServer
 * @Description TODO
 * @Author 11
 * @Date 2021/3/31 14:34
 * @Version 1.0
 */
@Component
public class BioServer implements ApplicationListener<ContextRefreshedEvent> {

    public static ApplicationContext applicationContext;
    private static int PORT =9000;
    private static ServerSocket serverSocket;

    static ExecutorService executorService = Executors.newCachedThreadPool();

    public BioServer(ApplicationContext applicationContext){
        BioServer.applicationContext = applicationContext;
    }
    public static void start(){
        if (serverSocket!=null){
            return;
        }
        try {
            serverSocket = new ServerSocket(PORT);
            System.out.println("rpc服务器启动成功，准备接受请求！");
            while (true){
                System.out.println("rpc服务器监听中！");
                Socket socket = serverSocket.accept();
                executorService.submit(new ServerHandler(socket));
                System.out.println("rpc服务器接收到请求！"+socket.getRemoteSocketAddress().toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (serverSocket!=null){
                    serverSocket.close();
                    System.out.println("rpc服务器已关闭！");
                    serverSocket=null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println("退出服务！");

    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        new Thread(){
            @Override
            public void run() {
                super.run();
                BioServer.start();

            }
        }.start();
    }
}
